package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final long SHIFT_LEFT = 32;
    private static final long BEGIN_TIMESTAMP = 1735689600L;
    public long nextId (String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long nowSecond = epochSecond - BEGIN_TIMESTAMP;
        // 生成序列号
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + nowSecond);
        // 拼接后返回
        return nowSecond << SHIFT_LEFT | increment;
    }

}
